package com.liu.dao.jdbc;

import com.liu.util.DBHandler;
import com.liu.util.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author 老刘Matthew
 * @Timestamp 2022/7/13 23:09
 * @Description
 *
 * JdbcTemplate<T>              JDBC模块方法类，封装基础通用查询
 * GenericDaoImpl<T>            Dao通过查询类，由子业务表Dao类分别继承，复用查询物料及模板
 * ResultSetCallback<T>         回调函数式接口，适用查询结果集为List场景
 * ResultSingleCallBack<T>      回调函数式接口，适用查询结果集为Object场景
 * DaoFactory                   单例工厂，封装复用Dao类组件
 *
 */
public final class JdbcTemplate<T> implements LoggerFactory {

    private ResultSet executeQuery(String sql) {
    	
        try {
        	
        	Connection connection = DBHandler.getConnection();
            PreparedStatement statement = connection.prepareStatement(sql);
        	
            return statement.executeQuery();

        } catch (Exception e) {
            logger.error("JDBC连接异常！", e);
        }

        return null;
    }

    public List<T> query(String sql, ResultSetCallback<T> callback) throws SQLException {
    	
    	logger.info("----------> execute query: " + sql);

        ResultSet resultSet = executeQuery(sql);

        return callback.mapResult(resultSet);
    }

    public T queryObject(String sql, ResultSingleCallBack<T> callback) throws SQLException {
    	
    	logger.info("----------> execute queryObject: " + sql);

        ResultSet resultSet = executeQuery(sql);
        
        return callback.mapResult(resultSet);
    }

    public Integer updateOrInsert(String sql, Object[] attrs, Integer[] types)  throws SQLException {

    	logger.info("----------> execute updateOrInsert: " + sql);
    	
        if(attrs.length != types.length) {
            logger.error("参数列表attrs_types不匹配！", new SQLException());
            return 0;
        }

        try (
                Connection connection = DBHandler.getConnection();
                PreparedStatement statement = connection.prepareStatement(sql);
        ) {

            for (int i = 0; i < attrs.length; i++)
                statement.setObject(i + 1, attrs[i], types[i]);
            return statement.executeUpdate();

        } catch (Exception e) {
            logger.error("JDBC连接异常！", e);
        }

        return 0;
    }

}
